package com.hn.zhijian.cloud.config;

import com.alibaba.fastjson.JSON;
import com.hn.zhijian.base.common.StatusCode;
import com.hn.zhijian.base.common.exception.ApplicationException;
import com.hn.zhijian.base.model.response.Response;
import feign.FeignException;
import feign.codec.Decoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Optional;

/**
 * @author carl
 */
@Slf4j
public class SpringCloudResponseEntityDecoder extends ResponseEntityDecoder {

    public SpringCloudResponseEntityDecoder(Decoder decoder) {
        super(decoder);
    }

    @Override
    public Object decode(feign.Response response, Type type) throws IOException, FeignException {


        Response modeBody =  JSON.parseObject(Optional.ofNullable(super.decode(response, type))
                .map(o1 -> o1.toString()).orElse(""), Response.class);

        log.info(JSON.toJSONString(modeBody));

        if(modeBody.getCode() != StatusCode.OK.getCode()){
            //如果是错误就给出提示
            throw new ApplicationException(modeBody.getCode(),modeBody.getMessage());
        }

        return modeBody.getBody();
    }
}
